package com.miguo.app;

import android.content.Context;
import android.provider.Settings;

import com.alibaba.sdk.android.AlibabaSDK;
import com.alibaba.sdk.android.callback.InitResultCallback;
import com.alibaba.sdk.android.trade.TradeConfigs;
import com.alibaba.sdk.android.trade.TradeConstants;
import com.alibaba.sdk.android.trade.callback.TradeProcessCallback;
import com.alibaba.sdk.android.trade.model.TradeResult;
import com.miguo.bean.UserBean;
import com.miguo.db.DaoMaster;
import com.miguo.db.DaoMaster.OpenHelper;
import com.miguo.db.DaoSession;
import com.miguo.framework.app.AppFramework;
import com.miguo.plugins.Statistics;
import com.miguo.plugins.UmengPush;
import com.miguo.plugins.UmengUp;
import com.miguo.utils.ApiPrefs;
import com.miguo.utils.CommonUtils;
import com.miguo.utils.ConfigInfo;
import com.mrper.util.DeviceUtil;

import java.util.Map;

public class AppContext {

    private static AppContext instance;
    private static Context mContext;
    private static ApiPrefs Prefs;
    private static UserBean UserInfo;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    public static String sImei;
    public static String sImsi;
    public static String REDIRECT_URI = "meguo://uri";// URI回调

    public static boolean isNoImg = false;// 2/3G是否开启无图
    public static boolean isOpenNight = false;
    public static boolean isTaobaoInstalled = false;// 淘宝客户端是否安装
    public static boolean isTmallInstalled = false;// 天猫客户端是否安装
    public static boolean isNetwork = true;// 检查网络状态
    public static boolean isAilError = false;// 检查网络状态

    /** 全局跳转类型 1:自身web(百川URL页) 2:自身详细页(原生详情页)，添加日期：2016-04-26   **/
    public static int GlobalJumpType = 1;

    public static AppContext init(Context context) {
        if (instance == null) {
            instance = new AppContext(context);
        }
        return instance;
    }

    private AppContext(Context context) {
        mContext = context;

        //初始化阿里百川配置
        initAlibabaConfig();
        //初始化默认参数配置
        initParamConfig();
        // 友盟统计与腾讯统计
        Statistics.init();
        /* 友盟推送 */
        UmengPush.init(mContext);
        UmengPush.onAppStart(mContext);
        /* 友盟更新 */
        UmengUp.init();
    }

    public static AppContext getInstance() {
        return instance;
    }

    public static Context getContext() {
        return mContext;
    }

    private void initAlibabaConfig() {
        /**
         * 指定商品详情页面类型
         * TradeConfigs.defaultItemDetailWebViewType
         *
         * @param TradeConstants.BAICHUAN_H5_VIEW 百川 H5 页面
         * @param TradeConstants.TAOBAO_H5_VIEW 淘宝 H5 页面
         * @param TradeConstants.TAOBAO_NATIVE_VIEW 唤起手淘详情页
         */
        TradeConfigs.defaultItemDetailWebViewType = TradeConstants.BAICHUAN_H5_VIEW;

        /**
         * TradeConfigs.defaultTradeProcessCallback
         *
         * 默认的交易回调，当调用默认交易相关方法未指定交易回调时会使用
         */
        TradeConfigs.defaultTradeProcessCallback = new TradeProcessCallback() {

            @Override
            public void onPaySuccess(TradeResult tradeResult) {
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        };

        /**
         *
         * TradeConfigs.defaultTaokePid :
         * 默认的淘客 Pid 值, 在调用淘客相关方法时未指定 pid，建议指定该值。
         *
         * TradeConfigs.defaultISVCode :
         * 可定制 ISV code(不多于50个字符，支持英文字符&数字&_(下划线) 不要使用特殊符号)，会透传至交易流程，在消息通知功能中，获取交易订单消息能获取到这个字段。
         *
         */
        Map<String, String> defaultParam = AppFramework.getDefaultParam();
        String ISVCode = defaultParam.get("platform") + "_" + defaultParam.get("channel") + "_" + defaultParam.get("app_version");
        TradeConfigs.defaultTaokePid = AppConfig.TAOCONFIG.PID;
        TradeConfigs.defaultISVCode = ISVCode;
        AlibabaSDK.asyncInit(mContext, new InitResultCallback() {

            @Override
            public void onSuccess() {
                // Log.i("AlibabaSDK-asyncInit-初始化成功");
                isAilError = false;
            }

            @Override
            public void onFailure(int code, String message) {
                //Log.e("AlibabaSDK-asyncInit-初始化异常-code:"+code+":message"+message);
                isAilError = true;
            }

        });
    }

    private void initParamConfig() {
//        CommonUtil.setStaticsChannel(mContext);//获取渠道名称
        ConfigInfo.startConfigRequest(mContext);//开始数据配置操作请求

        isTaobaoInstalled = CommonUtils.apkIsInstall(mContext,
                "com.taobao.taobao");
        isTmallInstalled = CommonUtils.apkIsInstall(mContext,
                "com.tmall.wireless");

        AppContext.sImei = DeviceUtil.getPhoneIMEI(mContext);
        AppContext.sImsi = DeviceUtil.getPhoneIMSI(mContext);

    }

    public static ApiPrefs Prefs() {
        if (Prefs == null) {
            Prefs = ApiPrefs.init();
        }

        return Prefs;
    }

    public static UserBean UserInfo() {
        if (UserInfo == null) {
            UserInfo = new UserBean();
        }

        return UserInfo;
    }

    public static String getAndroidId() {
        String id = Settings.Secure.getString(mContext.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        return id;
    }

    /**
     * 取得DaoMaster
     *
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context) {
        try {
            if (daoMaster == null) {
                OpenHelper helper = new DaoMaster.DevOpenHelper(context,
                        AppConfig.DB_NAME, null);
                daoMaster = new DaoMaster(helper.getWritableDatabase());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return daoMaster;
    }

    /**
     * 取得DaoSession
     *
     * @param context
     * @param clearSession
     * @return
     */
    public static DaoSession getDaoSession(Context context, boolean clearSession) {
        if (daoSession == null || clearSession) {
            if (daoMaster == null || clearSession) {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

}
